package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.ProductStockMapper;
import cn.wolfcode.crm.mapper.StockOutcomeBillMapper;
import cn.wolfcode.crm.mapper.StockOutcomeBillitemMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IStockOutcomeBillService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class StockOutcomeBillServiceImpl implements IStockOutcomeBillService {
    @Autowired
    private StockOutcomeBillMapper stockOutcomeBillMapper;
    @Autowired
    private StockOutcomeBillitemMapper stockOutcomeBillitemMapper;

    @Autowired
    private ProductStockMapper productStockMapper;


    @Override
    public void deleteByPrimaryKey(Long id) {
        stockOutcomeBillMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void     saveOrUPdate(StockOutcomeBill s) {
        if (s.getId()==null) {
            saveBill(s);
        }else {
            updateBill(s);
        }
    }

    //保存订单
    public void saveBill(StockOutcomeBill d){
        //设置录入时间
        d.setInputTime(new Date());
        //设置订单状态
        d.setStatus(StockOutcomeBill.NORMAL);
        //定义两个变量,来记录当前单据的总数量和总价
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        //设置明细数据
        for (StockOutcomeBillitem item : d.getItems()) {
           //计算单据的小计, 单价*数量四舍五入保留两位小数
            BigDecimal amount = item.getSalePrice().multiply(item.getNumber())
                    .setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //叠加总数量和总价
            totalNumber = totalNumber.add(item.getNumber());
            totalAmount = totalAmount.add(amount);
        }
        //设置单据的总价和总数量
        d.setTotalNumber(totalNumber);
        d.setTotalAmount(totalAmount);
        //保存单据
        stockOutcomeBillMapper.insert(d);
        //保存明细
        for (StockOutcomeBillitem item : d.getItems()) {
            //保存明细到数据库
            item.setBillId(d.getId());
            stockOutcomeBillitemMapper.insert(item);
        }
    }

    //更新订单
    public void updateBill(StockOutcomeBill d){
        //根据单据的ID查询完整的单据信息
        StockOutcomeBill old = stockOutcomeBillMapper.selectByPrimaryKey(d.getId());
        //检验当前单据的状态,未审核才能更新
        if (old.getStatus() != StockOutcomeBill.NORMAL) {
            //重新计算明细小计,单据的总数量和总价格
            //删除当前单据所有的明细
            stockOutcomeBillitemMapper.deleteItemByBillId(old.getId());
            //定义变量来记录总数和总价
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            //计算单据的总价和总数量
            for (StockOutcomeBillitem item : d.getItems()) {
                BigDecimal amount = item.getSalePrice().multiply(item.getNumber())
                        .setScale(2, RoundingMode.HALF_UP);
                item.setAmount(amount);
                //叠加总数量和总价
                totalNumber = totalNumber.add(item.getNumber());
                totalAmount = totalAmount.add(amount);
                //保存明细
                item.setBillId(d.getId());
                stockOutcomeBillitemMapper.insert(item);
            }
            //回填订单数据
            d.setTotalNumber(totalNumber);
            d.setTotalAmount(totalAmount);
            //5:更新订单
            stockOutcomeBillMapper.updateByPrimaryKey(d);
        }
    }

    @Override
    public StockOutcomeBill selectByPrimaryKey(Long id) {
        return stockOutcomeBillMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<StockOutcomeBill> selectAll() {
        return stockOutcomeBillMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int total = stockOutcomeBillMapper.selectCount(qo);
        if(total==0){
            return new PageResult(total, Collections.EMPTY_LIST);
        }
        List<StockOutcomeBill> rows = stockOutcomeBillMapper.queryForList(qo);
        return new PageResult(total,rows);
    }


    public void audit(Long id) {
        //根据单据的ID查询完整的单据信息
        StockOutcomeBill bill = stockOutcomeBillMapper.selectByPrimaryKey(id);
        //检验当前单据的状态,未审核才能更新
        if (bill.getStatus() == StockOutcomeBill.NORMAL) {
            Depot d = bill.getDepot();
            //1:迭代当前单据中所有的明细,依次入库
            for (StockOutcomeBillitem item : bill.getItems()) {
                //1:查询该仓库中是否有该商品
                Product p = item.getProduct();
                //============出库操作==============
                //2:该商品在该仓库中没有库存
                ProductStock ps = productStockMapper.selectByProductAndDepot(p.getId(), d.getId());
                if (ps == null){ //该商品在仓库中没有库存
                    String msg = "仓库:["+d.getName()+"]没有["+p.getName()+"]商品的库存";
                    throw new RuntimeException(msg);
                }
                //3:检查库存数量是否满足出库的数量
                if (item.getNumber().compareTo(ps.getStoreNumber()) > 0) {
                    String msg = "仓库:["+d.getName()+p.getName()+"]商品的库存是:"+ps.getStoreNumber()
                            +",不足出库数量:"+item.getNumber();
                    throw new RuntimeException(msg);
                }
                //4:满足出库要求,减少总价值,减少总数量
                BigDecimal am = ps.getPrice().multiply(item.getNumber())
                        .setScale(2, RoundingMode.HALF_UP);
                BigDecimal amount = ps.getAmount().subtract(am);
                ps.setAmount(amount);
                BigDecimal num = ps.getStoreNumber().subtract(item.getNumber());
                ps.setStoreNumber(num);
                //5:更新库存
                productStockMapper.updateByPrimaryKey(ps);

            }
            //设置单据的状态
            bill.setStatus(StockOutcomeBill.AUDIT);
            stockOutcomeBillMapper.audit(bill);
        }
    }
}
